package com.qnbc.mystery.domain;


import java.util.*;

/**
 * @author gzj
 * @description 魔力赏抽奖实体类
 * @date 2024/2/20 09:38
 */

public class SingleWinnerLottery {

    private Map<String, Double> categoryProbabilities;

    private Map<String, Integer> categoryQuantities;

    public SingleWinnerLottery(Map<String, Double> categoryProbabilities, Map<String, Integer> categoryQuantities) {
        this.categoryProbabilities = categoryProbabilities;
        this.categoryQuantities = categoryQuantities;
    }

    public String drawWinner() {
        Random random = new Random();
        double totalProbability = categoryProbabilities.values().stream().mapToDouble(Double::doubleValue).sum();
        double randomNumber = random.nextDouble() * totalProbability;
        double cumulativeProbability = 0.0;
        for (Map.Entry<String, Double> entry : categoryProbabilities.entrySet()) {
            cumulativeProbability += entry.getValue();
            if (randomNumber <= cumulativeProbability && categoryQuantities.get(entry.getKey()) > 0) {
                categoryQuantities.put(entry.getKey(), categoryQuantities.get(entry.getKey()) - 1);
                return entry.getKey();
            }
        }
        return null;
    }


}
